{include file='header'/}
<body class="pear-admin">
<div class="main-container">
    <form class="layui-form" id="custom-config-edit-form" method="post">
        <div class="layui-form-item">
            <label class="layui-form-label required">配置名称</label>
            <div class="layui-input-block">
                <input type="text" name="name" required lay-verify="required|name" autocomplete="off"
                       placeholder="必须是英文开头，允许带数字下划线" class="layui-input readonly-bg" value="" readonly>
            </div>
            <tip>名称必须是英文开头，允许带数字下划线，长度1-20位</tip>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">简洁说明</label>
            <div class="layui-input-block">
                <input type="text" name="title" required lay-verify="required" autocomplete="off" class="layui-input"
                       placeholder="例如：这个是站点QQ">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">配置类型</label>
            <div class="layui-input-inline">
                <input type="hidden" name="fieldtype">
                <select name="fieldtype" lay-filter="configFieldType" style="width:230px">
                    {foreach name='field_type' id='vo' key='k'}
                    <option value="{$k}">{$vo}</option>
                    {/foreach}
                </select>
            </div>
        </div>
        <div class="layui-form-item" style="z-index:0">
            <label class="layui-form-label">配置值</label>
            <div class="layui-input-block custom-config-mode config_mode_text">
                <input type="text" name="value[text]" autocomplete="off" placeholder="" value=""
                       class="layui-input">
            </div>

            <div class="layui-input-block custom-config-mode config_mode_textarea" style="display:none">
                <textarea class="layui-textarea" name="value[textarea]"
                          placeholder="例如：214243830"></textarea>
            </div>
            <!--<div class="layui-input-block custom-config-mode config_mode_image huicmf-upload"
                 style="display:none">
                <div class="layui-input-block-flex">
                    <input type="text" name="value[image]" id="custom-config-image-select-input" autocomplete="off"
                           class="layui-input" onmouseover="layui.huiAdmin.huiImgPreview('upload_pic_custom_config',this.value)"
                           onmouseleave="layer.tips();">
                    <button type="button" class="layui-btn layui-btn-normal layUpload"
                            data-multiple="false" data-input-id="custom-config-image-select-input"
                            id="upload_pic_custom_config"
                            data-preview-id="custom-config-image" data-type="image"><i class="layui-icon"></i>上传图片
                    </button>
                    <button type="button" class="layui-btn" style="margin-left:10px;"
                            data-open-pic="/app/admin/upload/choose?type=one&select_id=custom-config-image-select-input">
                        <i class="layui-icon"></i>选择图片
                    </button>
                </div>
                <div>
                    <div id="custom-config-image-select-input_box" class="upload_pic_box">
                    </div>
                </div>
            </div>-->
            <div class="layui-input-block custom-config-mode config_mode_image" style="display: none">
                <a class="layui-btn"
                   data-open-pic="/app/admin/upload/choose?type=one&select_id=custom-config-image-select-input-one">
                    <i class="layui-icon">&#xe67c;</i>选择图片
                </a>
                <!--回调显示选择的图片-->
                <div class="uploader-list am-cf" id="custom-config-image-select-input-one" data-name="value[image][]">

                </div>
            </div>
            <div class="layui-input-block custom-config-mode config_mode_images" style="display: none">
                <a class="layui-btn"
                   data-open-pic="/app/admin/upload/choose?type=more&select_id=custom-config-image-select-input-more">
                    <i class="layui-icon">&#xe67c;</i>选择图片
                </a>
                <tip>(可拖拽图片调整显示顺序 )</tip>
                <!--回调显示选择的图片-->
                <div class="uploader-list am-cf" id="custom-config-image-select-input-more" data-name="value[images][]">

                </div>
            </div>

            <div class="layui-input-block custom-config-mode config_mode_radio" style="display:none">

            </div>
            <div class="layui-input-block custom-config-mode config_mode_select" style="display:none">

            </div>
            <div class="layui-input-block custom-config-mode config_mode_date" style="display:none">
                <input type="text" id="custom-config-input-date" name="value[date]" autocomplete="off" value=""
                       class="layui-input" placeholder="yyyy-MM-dd">
            </div>

            <div class="layui-input-block custom-config-mode config_mode_datetime" style="display:none">
                <input type="text" id="custom-config-input-datetime" name="value[datetime]" autocomplete="off" value=""
                       class="layui-input" placeholder="yyyy-MM-dd HH:mm:ss">
            </div>

            <div class="layui-input-block custom-config-mode config_mode_editor" style="display:none;">
                {php}echo
                support\lib\Form::editor('value[editor]','custom-config-editor','','width:100%;height:400px');{/php}
            </div>

        </div>

        <div class="bottom">
            <div class="button-container">
                <button type="submit" class="layui-btn layui-btn-sm" lay-submit="">
                    <i class="layui-icon layui-icon-ok"></i>
                    提交
                </button>
                <button type="reset" class="layui-btn layui-btn-primary layui-btn-sm">
                    <i class="layui-icon layui-icon-refresh"></i>
                    重置
                </button>
            </div>
        </div>

    </form>

    <table class="layui-table" id="custom-config-form-table-create" style="display: none">
        <thead>
        <tr>
            <th>标题-name</th>
            <th width="30%">值-value</th>
            <th width="65">操作</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td colspan="2">请输入对应的标题和值</td>
            <td style="text-align: center">
                <div class="layui-btn-group">
                    <button type="button" class="layui-btn layui-btn-sm custom-config-btn-add">新增</button>
                </div>
            </td>
        </tr>
        </tbody>
    </table>
</div>
</body>
{include file='footer'/}
<script>
  let PRIMARY_KEY = "name";
  let PRIMARY_KEY_VALUE = "{:request()->get('name')}";
  layui.use(["form", "laydate", "upload_hui", "ddSort"], function () {
    var $ = layui.$;
    var form = layui.form;
    var laydate = layui.laydate;
    var upload_hui = layui.upload_hui;
    upload_hui.render();
    form.render();

    //多图图片列表拖动，需要引入ddSort
    $('.uploader-list').DDSort({
      target: '.file-item',
      delay: 100, // 延时处理，默认为 50 ms，防止手抖点击 A 链接无效
      floatStyle: {
        'border': '1px solid #ccc',
        'background-color': '#fff'
      }
    });

    laydate.render({
      elem: '#custom-config-input-date'
      , type: 'date'
    });

    laydate.render({
      elem: '#custom-config-input-datetime'
      , type: 'datetime'
    });

    window.conf_index = 0;
    layui.$.ajax({
      url: "/app/admin/customconfig/select?name=" + PRIMARY_KEY_VALUE,
      dataType: "json",
      success: function (res) {
        let data = res.data[0];
        layui.$('input[name="name"]').val(data.name);
        layui.$('input[name="title"]').val(data.title);
        layui.$('input[name="fieldtype"]').val(data.fieldtype);
        layui.$("select[name=fieldtype]").val(data.fieldtype);
        layui.$("select[name=fieldtype]").attr('disabled', 'disabled');
        $('.custom-config-mode').hide();
        $('.config_mode_' + data.fieldtype).show();

        if (data.fieldtype === 'textarea') {
          layui.$('textarea').val(layui.util.escape(data.value));
        } else if (data.fieldtype === 'editor') {
          editor.setHtml(data.value)
        } else if (data.fieldtype === 'radio' || data.fieldtype === 'select') {
          var str = '';
          conf_index = data.value.length;
          layui.each(data.value, function (index, item) {
            str += '<tr>';
            str += '<td><input type="text" name="value[more][' + index + '][name]" required lay-verify="required" placeholder="标题" autocomplete="off" class="layui-input" value="' + item.value + '"></td>';
            str += '<td><input type="text" name="value[more][' + index + '][value]" required lay-verify="required" placeholder="值" autocomplete="off" class="layui-input" value="' + item.value + '"></td>';
            str += '<td style="text-align: center">';
            str += '<button type="button" class="layui-btn layui-btn-danger layui-btn-xs custom-config-form-add-table-del">删除</button>';
            str += '</td>';
            str += '</tr>';
          });
          $('.config_mode_' + data.fieldtype).append($('#custom-config-form-table-create'));
          $('#custom-config-form-table-create').css('display', 'inline-table');
          layui.$('#custom-config-form-table-create').find('tbody tr').after(str);
        } else if (data.fieldtype === 'image') {
          let str = '';
          // 修复：添加 JSON 格式验证
          if (data.value !== null && data.value !== '' && data.value !== '""') {
            try {
              // 先检查是否已经是对象或数组，避免重复解析
              if (typeof data.value === 'string') {
                data.value = JSON.parse(data.value);
              }
              // 确保解析后是数组
              if (Array.isArray(data.value)) {
                layui.each(data.value, function (index, item) {
                  str += '<div class="file-item file-item-id-' + index + '">\n' +
                    '    <img src="' + item + '" onclick="layui.huiAdmin.bigMapImg(\'#custom-config-image-select-input-one\')">\n' +
                    '    <input name="value[image][]" type="hidden"\n' +
                    '           value="' + item + '">\n' +
                    '    <i class="layui-icon layui-icon-edit file-item-edit"></i>' +
                    '    <i class="layui-icon layui-icon-close file-item-delete" data-id="' + index + '"></i>\n' +
                    '</div>';
                });
              } else if (typeof data.value === 'string') {
                // 如果是单个字符串值
                str += '<div class="file-item file-item-id-0">\n' +
                  '    <img src="' + data.value + '" onclick="layui.huiAdmin.bigMapImg(\'#custom-config-image-select-input-one\')">\n' +
                  '    <input name="value[image][]" type="hidden"\n' +
                  '           value="' + data.value + '">\n' +
                  '    <i class="layui-icon layui-icon-edit file-item-edit"></i>' +
                  '    <i class="layui-icon layui-icon-close file-item-delete" data-id="0"></i>\n' +
                  '</div>';
              }
            } catch (e) {
              console.error('JSON解析错误:', e);
              // 如果解析失败，当作普通字符串处理
              if (typeof data.value === 'string' && data.value.trim().length > 0) {
                str += '<div class="file-item file-item-id-0">\n' +
                  '    <img src="' + data.value + '" onclick="layui.huiAdmin.bigMapImg(\'#custom-config-image-select-input-one\')">\n' +
                  '    <input name="value[image][]" type="hidden"\n' +
                  '           value="' + data.value + '">\n' +
                  '    <i class="layui-icon layui-icon-edit file-item-edit"></i>' +
                  '    <i class="layui-icon layui-icon-close file-item-delete" data-id="0"></i>\n' +
                  '</div>';
              }
            }
          }
          $('#custom-config-image-select-input-one').html(str);
          // 绑定删除事件
          $('.file-item-delete').on('click', function () {
            var id = $(this).data('id');
            layui.huiAdmin.fileItemDelete(id);
          });
        } else if (data.fieldtype === 'images') {
          let str = '';
          // 修复：添加 JSON 格式验证
          if (data.value !== null && data.value !== '' && data.value !== '""') {
            try {
              // 先检查是否已经是对象或数组，避免重复解析
              if (typeof data.value === 'string') {
                data.value = JSON.parse(data.value);
              }
              if (Array.isArray(data.value)) {
                layui.each(data.value, function (index, item) {
                  str += '<div class="file-item file-item-id-' + index + '">\n' +
                    '    <img src="' + item + '" onclick="layui.huiAdmin.bigMapImg(\'#custom-config-image-select-input-more\')">\n' +
                    '    <input name="value[images][]" type="hidden"\n' +
                    '           value="' + item + '">\n' +
                    '    <i class="layui-icon layui-icon-edit file-item-edit"></i>' +
                    '    <i class="layui-icon layui-icon-close file-item-delete" data-id="' + index + '"></i>\n' +
                    '</div>';
                });
              }
            } catch (e) {
              console.error('JSON解析错误:', e);
            }
          }
          $('#custom-config-image-select-input-more').html(str);

          // 绑定删除事件
          $('.file-item-delete').on('click', function () {
            var id = $(this).data('id');
            layui.huiAdmin.fileItemDelete(id);
          });
        } else {
          // 处理其他类型
          layui.$('input[name="value[' + data.fieldtype + ']"]').val(data.value);
        }

        layui.$('.custom-config-form-add-table-del').on('click', function () {
          $(this).parents('tr').remove()
        });
        form.render('select');
      }
    });

    form.on('select(configFieldType)', function (data) {
      $('.custom-config-mode').hide();
      if (data.value === 'radio' || data.value === 'select') {
        $('#custom-config-form-table-create').css('display', 'inline-table');
        $('.config_mode_' + data.value).append($('#custom-config-form-table-create'));
      }
      $('.config_mode_' + data.value).show();
    });

    $('.custom-config-btn-add').on('click', function () {
      var _fieldId = conf_index++;
      var element = $([
        '<tr>',
        '<td><input type="text" name="value[more][' + _fieldId + '][name]" lay-verify="required" placeholder="标题" autocomplete="off" class="layui-input" value=""></td>',
        '<td><input type="text" name="value[more][' + _fieldId + '][value]" lay-verify="required" placeholder="值" autocomplete="off" class="layui-input" value=""></td>',
        '<td style="text-align: center">',
        '<button type="button" class="layui-btn layui-btn-danger layui-btn-xs custom-config-form-add-table-del">删除</button>',
        '</td>',
        '</tr>',
      ].join(''));
      element.find('.custom-config-form-add-table-del').on('click', function () {
        $(this).parents('tr').remove();
      })
      $('#custom-config-form-table-create tbody').append(element);
    });

  });
</script>
